local skynet    = require "skynet"
local cjson     = require "cjson"
local http      = require("http.httpc")
require "skynet.manager"

local CMD = {}
local host = "https://developer.toutiao.com"

local header = {
    ["content-type"] = "application/json"
}

local cache = {
    tokens = {},
}

local function requestAccessToken(appid, secret)
    local url = "/api/apps/v2/token"
    local args = {
        appid = appid,
        secret = secret,
        grant_type = "client_credential"
    }
    local statuscode, resp_str = http.request("POST", host, url, {}, header, cjson.encode(args))
    if statuscode ~= 200 then
        error("requestAccessToken statuscode failed")
    end
    local ok, resp = pcall(cjson.decode, resp_str)
    if ok then
        if resp.err_no == 0 then
            cache.tokens[appid] = {
                token   = resp.data.access_token,
                exires  = skynet.time() + resp.expires_in,
            }
        else
            error(resp_str)
        end
    else
        error(resp_str)
    end
end

function CMD.getAccessToken(appid, secret)
    local token = cache.tokens[appid]
    if not token or skynet.time() - 3600 > token.exires then
        requestAccessToken(appid, secret)
        return cache.tokens[appid].token
    end
    return token.token
end



skynet.start(function()
    skynet.dispatch("lua", function(_, _, command, ...)
        -- skynet.trace()
        local f = CMD[command]
        skynet.ret(skynet.pack(f(...)))
    end)
    skynet.register "cache"
end)